package cn.hc.share.service.impl;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.hc.share.dao.ArticleDao;
import cn.hc.share.dao.ArticleMsgDao;
import cn.hc.share.dao.CommentDao;
import cn.hc.share.dao.TagDao;
import cn.hc.share.dao.UserDao;
import cn.hc.share.entity.Article;
import cn.hc.share.entity.ArticleMsg;
import cn.hc.share.entity.Comment;
import cn.hc.share.entity.Tag;
import cn.hc.share.entity.User;
import cn.hc.share.service.ArticleNotFindException;
import cn.hc.share.service.ArticleSaveException;
import cn.hc.share.service.ArticleService;
import cn.hc.share.service.BaseService;
import cn.hc.share.service.MenuService;
import cn.hc.share.service.TagService;
import cn.hc.share.service.UserNotFoundException;
import cn.hc.share.util.StringUtil;

@Service("articleService2")
public class ArticleServiceImpl2_bak implements ArticleService
{

	@Resource
	private UserDao userDao;

	@Resource
	private ArticleDao articleDao;

	@Resource
	private ArticleMsgDao articleMsgDao;

	@Resource
	private CommentDao commentDao;

	@Resource
	private TagService tagService;

	@Resource
	private MenuService menuService;

	@Resource
	private TagDao tagDao;

	// 获取文章
	public List<Article> getArticles(String menuId, String tagId, String title, String page_, String pageSize_)
	{
		List<String> menuIdList = null;
		if (StringUtil.isNotNull(menuId))
		{
			menuIdList = menuService.getMenuIds(menuId);
			menuIdList.add(menuId);
		}
		if (StringUtil.isNull(tagId))
		{
			tagId = null;
		} else
		{
			tagId = getTagIdByTagName(tagId);
			tagId = "%" + tagId + "%";
		}
		if (StringUtil.isNull(title))
		{
			title = null;
		} else
		{
			title = "%" + title + "%";
		}
		if (StringUtil.isNull(page_))
		{
			page_ = "1";
		}
		int page = Integer.valueOf(page_);
		int pageSize = Integer.valueOf(pageSize_);
		int start = pageSize * (page - 1);
		String category = "文章";
		List<Article> articles = articleDao.findAllArticleByPage(menuIdList, tagId, title, start, pageSize, category);

		for (Article article : articles)
		{
			String tagId2 = article.getTagId();
			String tagNames = changArticleTagIdsToTagNames(tagId2);
			if(StringUtil.isNotNull(tagNames)) {
				article.setTagId(tagNames);
			}
		}
		
		return articles;

	}
	
	public String changArticleTagIdsToTagNames(String tagIds) {
		String tagNames="";
		if (StringUtil.isNotNull(tagIds))
		{
			String[] tagIdList = tagIds.split(",");
			for (String tagId : tagIdList)
			{
				Tag tag = new Tag();
				tag.setId(tagId);
				List<Tag> tags = tagDao.findTag(tag);
				if (tags.size() > 0)
				{
					tagNames += tags.get(0).getName() + ",";
				}
			}
			tagNames = tagNames.substring(0, tagNames.length() - 1);
		}
		return tagNames;
	}
	

	// 保存文章
	@Transactional
	public Article saveArticle(String articleId, String authorId, String title, String cont, String menuId,
			String tagIds, String category)
	{
		// 解决中文乱码问题
		try
		{
			if (StringUtil.isNotNull(articleId))
			{
				articleId = URLDecoder.decode(articleId, "UTF-8");
			}
			if (StringUtil.isNotNull(authorId))
			{
				authorId = URLDecoder.decode(authorId, "UTF-8");
			}
			if (StringUtil.isNotNull(title))
			{
				title = URLDecoder.decode(title, "UTF-8");
			}

			if (StringUtil.isNotNull(cont))
			{
				cont = URLDecoder.decode(cont, "UTF-8");
			}

			if (StringUtil.isNotNull(menuId))
			{
				menuId = URLDecoder.decode(menuId, "UTF-8");
			}

			if (StringUtil.isNotNull(tagIds))
			{
				tagIds = URLDecoder.decode(tagIds, "UTF-8");
			}

			if (StringUtil.isNotNull(category))
			{
				category = URLDecoder.decode(category, "UTF-8");
			}

		} catch (UnsupportedEncodingException e)
		{
			throw new RuntimeException("保存文章失败!");
		}

		boolean flag = true;
		if (StringUtil.isNull(authorId))
		{
			throw new RuntimeException("文章作者为空!");
		}

		Article article = null;
		article = articleDao.findArticleById(articleId);
		Timestamp nowDate = null;
		if (article == null)
		{
			article = new Article();
			nowDate = new Timestamp(System.currentTimeMillis());
			article.setCreateTime(nowDate);
			flag = false;
		}

		article.setAuthor(authorId);
		if (StringUtil.isNotNull(title))
		{
			article.setTitle(title);
		}

		Timestamp lastModifyTime = new Timestamp(System.currentTimeMillis());

		article.setId(articleId);
		article.setLastModifyTime(lastModifyTime);
		if (StringUtil.isNotNull(cont))
		{
			article.setContent(cont);
		}
		if (StringUtil.isNotNull(menuId))
		{
			article.setMenuId(menuId);
		}
		if (StringUtil.isNotNull(tagIds))
		{
			// 保存文章设置的书签
//			String addTagsResult = tagService.addTags(tagIds, authorId);
//			article.setTagId(addTagsResult);

		}
		if (StringUtil.isNotNull(category))
		{
			article.setCategory(category);
		}

		System.out.println(article);

		int num = 0;
		if (flag)
		{
			num = articleDao.updateArticle(article);
		} else
		{
			num = articleDao.addArticle(article);
		}

		if (num != 1)
		{
			throw new ArticleSaveException("保存文章失败!");
		}

		return article;
	}

	// 查找草稿
	public Article findDraft(String authorId)
	{

		User user = userDao.findUserById(authorId);

		if (user == null)
		{
			throw new UserNotFoundException("该用户不存在!");
		}

		Article article = new Article();
		article.setAuthor(authorId);
		article.setCategory("草稿");

		Article draft = articleDao.findDraftByAuthor(article);

		if (draft == null)
		{
			System.out.println("草稿为空");
		}
		
		String tagNames = changArticleTagIdsToTagNames(draft.getTagId());
		draft.setTagId(tagNames);
		
		return draft;

	}

	// 根据文章id获取文章
	public Article getArticleById(String id)
	{
		if (StringUtil.isNull(id))
		{
			throw new RuntimeException("文章id为空!");
		}
		Article article = articleDao.findArticleById(id);
		if (article == null)
		{
			throw new ArticleNotFindException("文章不存在!");
		}
		
		String tagNames = changArticleTagIdsToTagNames(article.getTagId());
		article.setTagId(tagNames);
		return article;
	}

	// 获取文章总数
	public int getArticlesCount(String menuId, String tagId, String title)
	{
		List<String> menuIdList = null;
		if (StringUtil.isNotNull(menuId))
		{
			menuIdList = menuService.getMenuIds(menuId);
			menuIdList.add(menuId);
		}
		if (StringUtil.isNull(tagId))
		{
			tagId = null;
		} else
		{
			tagId = getTagIdByTagName(tagId);
			tagId = "%" + tagId + "%";
		}
		if (StringUtil.isNull(title))
		{
			title = null;
		} else
		{
			title = "%" + title + "%";
		}
		String category = "文章";
		int count = articleDao.countArticles(menuIdList, tagId, title, category);
		return count;
	}

	// 获取某一篇文章收藏/有用/无用信息
	public ArticleMsg getArticleMsgSuspend(String articleId, String author)
	{
		ArticleMsg articleMsg = null;
		if (StringUtil.isNotNull(articleId) && StringUtil.isNotNull(author))
		{
			articleMsg = articleMsgDao.findArticleMsg(articleId, author);
		}
		return articleMsg;
	}

	// 更新/新增ArticleMsg
	@Transactional
	public ArticleMsg updateArticleMsg(String articleId, String author, String collectState, String usefullState)
	{
		ArticleMsg articleMsg = null;
		articleMsg = articleMsgDao.findArticleMsg(articleId, author);
		Timestamp lastModifyTime = new Timestamp(System.currentTimeMillis());
		if (articleMsg == null)
		{
			articleMsg = new ArticleMsg();
			String id = UUID.randomUUID().toString();
			articleMsg.setId(id);
			articleMsg.setArticleId(articleId);
			articleMsg.setCurrentUser(author);
			if (StringUtil.isNotNull(collectState))
			{
				Timestamp collectTime = new Timestamp(System.currentTimeMillis());
				articleMsg.setCollectTime(collectTime);
				articleMsg.setCollectState(collectState);
			}
			if (StringUtil.isNotNull(usefullState))
			{
				articleMsg.setUsefullState(usefullState);
			}
			articleMsg.setLastModifyTime(lastModifyTime);
			int num = articleMsgDao.addArticleMsg(articleMsg);
			if (num != 1)
			{
				throw new RuntimeException("添加收藏、有用/无用信息失败!");
			}
			return articleMsg;

		} else
		{
			if (StringUtil.isNotNull(collectState))
			{
				articleMsg.setCollectState(collectState);
				Timestamp collectTime = new Timestamp(System.currentTimeMillis());
				articleMsg.setCollectTime(collectTime);
			}
			if (StringUtil.isNotNull(usefullState))
			{
				articleMsg.setUsefullState(usefullState);
			}
			articleMsg.setLastModifyTime(lastModifyTime);

			int num = articleMsgDao.updateArticleMsg(articleMsg);

			if (num != 1)
			{
				throw new RuntimeException("更新收藏、有用/无用信息失败!");
			}
			return articleMsg;
		}
	}

	// 统计有用/无用数量
	public Map<String, Integer> countArticleMsg(String articleId)
	{

		Map<String, Integer> map = new HashMap<String, Integer>();
		int countUseful = articleMsgDao.countArticleUse(articleId, BaseService.ARTICLE_USEFULE);
		int countUnUseful = articleMsgDao.countArticleUse(articleId, BaseService.ARTICLE_UNUSEFULE);
		map.put("useful", countUseful);
		map.put("unuseful", countUnUseful);
		return map;
	}

	// 访问量+1
	@Transactional
	public int addVisitArticle(String articleId)
	{
		Article article = articleDao.findArticleById(articleId);
		if (article == null)
		{
			throw new ArticleNotFindException("没有该文章");
		}
		int visitNum = article.getVisitNum();
		if (visitNum >= 1)
		{
			visitNum += 1;
		} else
		{
			visitNum = 1;
		}
		System.out.println("visitNum:" + visitNum);
		article.setVisitNum(visitNum);
		int updateArticle = articleDao.updateArticle(article);
		if (updateArticle != 1)
		{
			throw new ArticleSaveException("更新文章失败!");
		}
		return visitNum;
	}

	//获取标签的idByTagName
	public String getTagIdByTagName(String tagName){
		String tagId ="";
		Tag tag = new Tag();
		tag.setName(tagName);
		List<Tag> findTag = tagDao.findTag(tag);
		if(findTag.size()>0) {
			tagId = findTag.get(0).getId();
		}
		return tagId;
	}
	
	
	// 评论数量统计
	public int statistCommentsNum(String articleId)
	{
		int num = 0;
		if (StringUtil.isNotNull(articleId))
		{
			num = commentDao.countCommentsByArticleId(articleId);
		}
		return num;
	}
}
